<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordsQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table
        :data="roles"
        highlight-current-row
        v-loading="listLoading"
        @selection-change="selsChange"
        style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="角色名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="角色sn" width="120" sortable>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="5"
          :current-page="localPage"
          :total="totals"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">

        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="角色sn" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="分配权限" prop="permissions">
          <el-select v-model="editForm.permissions" multiple placeholder="请选择">
            <el-option
                v-for="item in permissionList"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分配菜单" >
          <el-cascader v-model="editForm.menus"
                       :options="menuTree"
                       :props="{
                  multiple: true ,
                  label:'name',//回显的数据
                  value:'id',//返回后端的数据
                }"
                       clearable></el-cascader>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>


export default {
  data() {
    return {
      filters: {
        name: ''
      },
      parent: '',
      roles: [],
      permissionList:[],
      title:'',
      totals: 0,
      localPage: 1,
      pageSize: 5,
      listLoading: false,
      sels: [],//列表选中列

      managers: [],

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      menuTree:[],
      editFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      editForm: {
        id: null,
        name: null,
        sn:null,
        menus:null,
        permissions:null,
      },

    }
  },
  methods: {

    getMenuTree(){
      this.$http.get("/role/menuTree")
          .then(res=>{
            this.menuTree = res.data;
          }).catch(res=>{
        this.$message.error("系统繁忙")
      })
    },

    getPermissionList(){
      this.$http.get("/permission")
          .then(res=>{

            this.permissionList = res.data;
          }).catch(res=>{
        this.$message.error("系统繁忙")
      })
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleCurrentChange(currentPage) {
      this.localPage = currentPage;
      this.getRoles();
    },
    keywordsQuery(){
      this.localPage=1;
      this.getRoles()
    },
    //获取用户列表
    getRoles() {
      let para = {
        localPage: this.localPage,
        pageSize: this.pageSize,
        keywords: this.filters.name
      };
      this.listLoading = true;
      //NProgress.start();
      this.$http.post("/role",para)
          .then(result => {
            this.listLoading = false;
            this.roles = result.data.data;
            this.totals = result.data.totals;
          }) .catch(result=>{
        this.$message.error("系统繁忙")
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        //let para = row.id ;
        this.$http.delete("/role/"+row.id)
            .then(result=>{
              //关闭忙灯框
              this.listLoading = false;
              if(result.data.success){
                this.$message.success("删除成功")
                //刷新
                this.getRoles()
              }else{
                this.$message.error(result.data.msg)
              }
            }).catch(() => {
          this.$message.error("系统繁忙,请稍后再试")
        })
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title="编辑"
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
     // this.getManagers();
      this.getMenuTree();
      this.getPermissionList();
      if(row.ownMenus){
        let menus=[];
        for(let i= 0;i<row.ownMenus.length;i++){
          let menu = row.ownMenus[i];
          let menuTmp = [];
          if (menu.parent_id!=null&&menu.parent_id!=''){
            menuTmp.push(menu.parent_id);
          }
          menuTmp.push(menu.id);
          menus.push(menuTmp);
        }
        this.editForm.menus = menus;
      }
    },
    //显示新增界面
    handleAdd: function () {
      this.title="新增"
      this.editFormVisible = true;
      this.getMenuTree();//加载菜单树
      //加载权限下拉列表
      this.getPermissionList();
      this.editForm = {
        id: null,
        name: null,
        sn:null,
        menus:1,
        permissions:null,
      };
      //this.getManagers();
     // this.getRoleTree();
    },

    //新增
    editSubmit: function () {

      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            let menusArr = para.menus;
            if(menusArr){
              let menusTmp = [];
              for (var i=0;i<menusArr.length;i++){
                let menuTmp = menusArr[i];
                menusTmp.push(menuTmp[menuTmp.length-1]);
              }
              para.menus = menusTmp;
            }
            this.$http.put("/role",para)
                .then(res=>{
                  //关闭模态框
                  this.editFormVisible = false;
                  //关闭忙灯框
                  this.editLoading = false;
                  if(res.data.success){
                    this.$message.success("新增成功")
                  }else{
                    this.$message.error(res.data.msg)
                  }
                  this.localPage=1;
                  this.getRoles()
                })
            /*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            addRole(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getRoles();
            });*/
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        //开启忙灯框
        this.listLoading = true;
        //NProgress.start();
        let para = { ids: ids };
        this.$http.patch("/role",ids)
            .then(res=>{
              this.listLoading = false;
              if (res.data.success){
                this.$message.success("删除成功")
                this.getRoles()
              }else{
                this.$message.error(result.data.msg)
              }
            })
        /*batchRemoveRole(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getRoles();
        });*/
      }).catch(() => {
        this.$message.error("系统繁忙,请稍后再试")
      });
    }
  },
  mounted() {
    this.getRoles();
  }
}

</script>

<style scoped>

</style>